package com.meirengu.webview.controller;

import com.meirengu.channel.service.*;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.utils.DateUtils;
import com.meirengu.webview.model.User;
import com.meirengu.webview.model.UserInfo;
import com.meirengu.webview.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-12-19 12:27
 */
@Controller
@RequestMapping("handRuleRetry")
public class HandRuleRetryController extends BaseController {

    @Autowired
    UserInfoService userInfoService;
    @Autowired
    UserService userService;
    @Autowired
    PingAnService pingAnService;
    @Autowired
    KwUserChannelService kwUserChannelService;
    @Autowired
    KwThirdbackService kwThirdbackService;
    @Autowired
    KwInterfaceRetryService kwInterfaceRetryService;
    @Autowired
    PACAService pacaService;
    @Autowired
    NiWoDaiService niWoDaiService;
    @Autowired
    HouBankService houBankService;
    @Autowired
    YiCaiDaoService yiCaiDaoService;
    @Autowired
    private KwXbbFilterService kwXbbFilterService;
    @Autowired
    private KwFjsFilterService kwFjsFilterService;
    @Autowired
    private KwCcicFilterService kwCcicFilterService;
    @Autowired
    private KwCyphFilterService kwCyphFilterService;
    @Autowired
    private KwYcdFilterService kwYcdFilterService;
    @Autowired
    private KwYcdPushService kwYcdPushService;
    @Autowired
    private KwXxjrFilterService kwXxjrFilterService;
    @Autowired
    private KwDfrzFilterService kwDfrzFilterService;
    @Autowired
    private KwDfrzPushService kwDfrzPushService;
    @Autowired
    private KwZhudaiFilterService kwZhudaiFilterService;
    @Autowired
    private KwZhudaiPushService kwZhudaiPushService;
    @Autowired
    private KwAydFilterService kwAydFilterService;
    @Autowired
    KwOperationLogService kwOperationLogService;

    Logger logger = LoggerFactory.getLogger(HandRuleRetryController.class);


    /**
     * 补发中腾信(由于规则修改重发)
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @param refuseMsg
     * @param channelCode
     * @throws Exception
     */
    @RequestMapping("/handRetryRuleZTX")
    public Result handRetryRuleZTX(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                   @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd,
                                   @RequestParam(value = "suited", required = false) String suited,
                                   @RequestParam(value = "refuseMsg", required = false) String refuseMsg,
                                   @RequestParam(value = "channelCode", required = true) String channelCode) throws Exception {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查找符合条件的接口发送记录
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(channelCode)) {
            map.put("channelCode", channelCode);
        }
        if (StringUtils.isNotBlank(suited)) {
            map.put("suited", suited);
        }
        if (StringUtils.isNotBlank(refuseMsg)) {
            map.put("refuseMsg", refuseMsg);
        }

        List<Map<String, Object>> kwUserChannelServiceListList = kwUserChannelService.getList(map);
        if (kwUserChannelServiceListList != null && kwUserChannelServiceListList.size() > 0) {
            for (Map<String, Object> userChannelMap : kwUserChannelServiceListList) {
                String id = userChannelMap.get("id").toString();
                String mobile = userChannelMap.get("mobile").toString();
                //查找用户信息
                User user = userService.getByMobile(mobile);
                UserInfo userInfo = userInfoService.getByUserId(user.getId());
                //组装接口数据
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    //校验是否有发送成功的记录
                    Map<String, Object> ycdctcparams = new HashMap<>();
                    ycdctcparams.put("interfaceCode", "ycdctc");
                    ycdctcparams.put("mobile", user.getMobile());
                    ycdctcparams.put("code", 1);
                    List<Map<String, Object>> existYcdctcPushList = kwYcdPushService.getList(ycdctcparams);
                    //已有成功发送记录
                    if (existYcdctcPushList != null && existYcdctcPushList.size() > 0) {
                        continue;
                    }
                    kwYcdFilterService.sendZTX(userInfo, user);
                }
            }
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 补发助贷网(由于规则修改重发)
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @param refuseMsg
     * @param channelCode
     * @throws Exception
     */
    @RequestMapping("/handRetryRuleZhuDai")
    public Result handRetryRuleZhuDai(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                      @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd,
                                      @RequestParam(value = "suited", required = true) String suited,
                                      @RequestParam(value = "refuseMsg", required = false) String refuseMsg,
                                      @RequestParam(value = "channelCode", required = true) String channelCode,
                                      @RequestParam(value = "citysStr", required = false) String citysStr) throws Exception {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查找符合条件的接口发送记录
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(channelCode)) {
            map.put("channelCode", channelCode);
        }
        if (StringUtils.isNotBlank(suited)) {
            map.put("suited", suited);
        }
        if (StringUtils.isNotBlank(refuseMsg)) {
            map.put("refuseMsg", refuseMsg);
        }

        List<Map<String, Object>> zhudaiFilterList = kwZhudaiFilterService.getList(map);
        kwOperationLogService.addOperationLog("1", " 推送渠道", "handRetryRuleZhuDai",
                "补发助贷网(由于规则修改重发)", createTimeBegin, createTimeEnd, "kw_zhudai_filter", zhudaiFilterList.size(),
                suited + "", refuseMsg, channelCode);
        if (zhudaiFilterList != null && zhudaiFilterList.size() > 0) {
            for (Map<String, Object> zhudaiFilterMap : zhudaiFilterList) {
                String mobile = zhudaiFilterMap.get("mobile").toString();
                //查找用户信息
                User user = userService.getByMobile(mobile);
                UserInfo userInfo = userInfoService.getByUserId(user.getId());
                //组装接口数据
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    //过滤地址
                    if (StringUtils.isNotBlank(citysStr)) {
                        String scity = userInfo.getScity();
                        if (!citysStr.contains(scity)) {
                            continue;
                        }
                    }

                    //校验是否有推送接口的记录
                    Map<String, Object> params = new HashMap<>();
                    params.put("interfaceCode", "zhudai");
                    params.put("mobile", mobile);
                    params.put("code", 1);
                    List<Map<String, Object>> existPush = kwZhudaiPushService.getList(params);
                    //已有推送记录
                    if (existPush != null && existPush.size() > 0) {
                        continue;
                    }
                    //获取上一天时间
                    long timemillis = DateUtils.getYesRanTime();
                    userInfo.setCreateDate(new Date(timemillis));
                    kwZhudaiFilterService.sendZhuDai(userInfo, user);
                }
            }
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    /**
     * 补发东方融资网(由于规则修改重发)
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @param refuseMsg
     * @throws Exception
     */
    @RequestMapping("/handRetryRuleEast")
    @ResponseBody
    public Result handRetryRuleEast(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                    @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd,
                                    @RequestParam(value = "suited", required = true) String suited,
                                    @RequestParam(value = "refuseMsg", required = false) String refuseMsg) throws Exception {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查找符合条件的接口发送记录
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(suited)) {
            map.put("suited", suited);
        }
        if (StringUtils.isNotBlank(refuseMsg)) {
            map.put("refuseMsg", refuseMsg);
        }
        List<Map<String, Object>> kwFilterList = kwDfrzFilterService.getList(map);
        kwOperationLogService.addOperationLog("1", " 推送渠道", "handRetryRuleEast",
                "手工补发东方融资网数据", createTimeBegin, createTimeEnd, "kwDfrzFilter", kwFilterList.size(),
                null, null, null);
        if (kwFilterList != null && kwFilterList.size() > 0) {
            for (Map<String, Object> userChannelMap : kwFilterList) {
                String id = userChannelMap.get("id").toString();
                String mobile = userChannelMap.get("mobile").toString();
                //查找用户信息
                User user = userService.getByMobile(mobile);
                UserInfo userInfo = userInfoService.getByUserId(user.getId());
                //组装接口数据
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    //校验是否有推送接口的记录
                    Map<String, Object> params = new HashMap<>();
                    params.put("interfaceCode", "dfrz-isregister");
                    params.put("mobile", mobile);
                    params.put("code", 1);
                    List<Map<String, Object>> kwPushList = kwDfrzPushService.getList(params);
                    //已有推送记录
                    if (kwPushList != null && kwPushList.size() > 0) {
                        continue;
                    }
                    kwDfrzFilterService.sendEastFinance(userInfo, user);
                }
            }
        }

        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    /**
     * 补发厚本金融(由于规则修改重发)
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @param refuseMsg
     * @param channelCode
     * @throws Exception
     */
    @RequestMapping("/handRetryRuleHouBank")
    public Result handRetryPinganHouBank(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                         @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd,
                                         @RequestParam(value = "suited", required = true) String suited,
                                         @RequestParam(value = "refuseMsg", required = false) String refuseMsg,
                                         @RequestParam(value = "channelCode", required = true) String channelCode,
                                         @RequestParam(value = "citysStr", required = false) String citysStr) throws Exception {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查找符合条件的接口发送记录
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(channelCode)) {
            map.put("channelCode", channelCode);
        }
        if (StringUtils.isNotBlank(suited)) {
            map.put("suited", suited);
        }
        if (StringUtils.isNotBlank(refuseMsg)) {
            map.put("refuseMsg", refuseMsg);
        }

        List<Map<String, Object>> kwUserChannelServiceListList = kwUserChannelService.getList(map);
        if (kwUserChannelServiceListList != null && kwUserChannelServiceListList.size() > 0) {
            for (Map<String, Object> userChannelMap : kwUserChannelServiceListList) {
                String id = userChannelMap.get("id").toString();
                String mobile = userChannelMap.get("mobile").toString();
                //查找用户信息
                User user = userService.getByMobile(mobile);
                UserInfo userInfo = userInfoService.getByUserId(user.getId());
                //组装接口数据
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    //过滤地址
                    if (StringUtils.isNotBlank(citysStr)) {
                        String scity = userInfo.getScity();
                        if (!citysStr.contains(scity)) {
                            continue;
                        }
                    }

                    //校验是否有推送接口的记录
                    Map<String, Object> params = new HashMap<>();
                    params.put("interfaceCode", "houbank-import");
                    params.put("mobile", mobile);
                    params.put("code", 1);
                    List<Map<String, Object>> existThirdback = kwThirdbackService.getList(params);
                    //已有推送记录
                    if (existThirdback != null && existThirdback.size() > 0) {
                        continue;
                    }
                    userInfoService.sendHouBank(userInfo, user);
                }
            }
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    /**
     * 补发所有接口(由于地址修改重发)
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @param refuseMsg
     * @param channelCode
     * @throws Exception
     */
    @RequestMapping("/handRetryRuleForAddr")
    public Result handRetryRuleForAddr(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                       @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd,
                                       @RequestParam(value = "suited", required = true) String suited,
                                       @RequestParam(value = "refuseMsg", required = false) String refuseMsg,
                                       @RequestParam(value = "channelCode", required = true) String channelCode,
                                       @RequestParam(value = "citysStr", required = false) String citysStr) throws Exception {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查找符合条件的接口发送记录
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        if (StringUtils.isNotBlank(channelCode)) {
            map.put("channelCode", channelCode);
        }
        if (StringUtils.isNotBlank(suited)) {
            map.put("suited", suited);
        }
        if (StringUtils.isNotBlank(refuseMsg)) {
            map.put("refuseMsg", refuseMsg);
        }
        String interfaceCode = "";
        switch (channelCode) {
            //平安普惠
            case "pinganpuhui":
                interfaceCode = "pinganph";
                break;
            //平安赠险
            case "pinganzenxian":
                interfaceCode = "pinganzx";
                break;
            //平安新一贷
            case "paca":
                interfaceCode = "newloan";
                break;
            //厚本金融
            case "houbank":
                interfaceCode = "houbank-import";
                break;
            default:
                interfaceCode = channelCode;

        }
        List<Map<String, Object>> kwUserChannelServiceListList = kwUserChannelService.getList(map);
        kwOperationLogService.addOperationLog("1", " 推送渠道", "handRetryRuleForAddr",
                "补发所有接口", createTimeBegin, createTimeEnd, "kw_user_channel", kwUserChannelServiceListList.size(),
                suited, refuseMsg, channelCode);
        if (kwUserChannelServiceListList != null && kwUserChannelServiceListList.size() > 0) {
            for (Map<String, Object> userChannelMap : kwUserChannelServiceListList) {
                String id = userChannelMap.get("id").toString();
                String mobile = userChannelMap.get("mobile").toString();
                //查找用户信息
                User user = userService.getByMobile(mobile);
                UserInfo userInfo = userInfoService.getByUserId(user.getId());
                //组装接口数据
                if (userInfo != null && StringUtils.isNotBlank(userInfo.getId())) {
                    //过滤地址
                    if (StringUtils.isNotBlank(citysStr)) {
                        String scity = userInfo.getScity();
                        if (!citysStr.contains(scity)) {
                            continue;
                        }
                    }

                    //校验是否有推送接口的记录
                    Map<String, Object> params = new HashMap<>();
                    params.put("interfaceCode", interfaceCode);
                    params.put("mobile", mobile);
                    params.put("code", 1);
                    List<Map<String, Object>> existThirdback = kwThirdbackService.getList(params);
                    //已有推送记录
                    if (existThirdback != null && existThirdback.size() > 0) {
                        continue;
                    }
                    if ("pinganpuhui".equals(channelCode)) {
                        userInfoService.sendPuHui(userInfo, user);
                    } else if ("pinganzenxian".equals(channelCode)) {
                        userInfoService.sendPingAnZX(userInfo, user);
                    } else if ("dfrz".equals(channelCode)) {
                        kwDfrzFilterService.sendEastFinance(userInfo, user);
                    } else if ("paca".equals(channelCode)) {
                        userInfoService.sendPcac(userInfo, user);
                    } else if ("ztx".equals(channelCode)) {
                        kwYcdFilterService.sendZTX(userInfo, user);
                    } else if ("zhudai".equals(channelCode)) {
                        kwZhudaiFilterService.sendZhuDai(userInfo, user);
                    } else if ("fanggold".equals(channelCode)) {
                        kwFjsFilterService.sendFangGold(userInfo, user);
                    } else if ("houbank".equals(channelCode)) {
                        userInfoService.sendHouBank(userInfo, user);
                    } else if ("xxjr".equals(channelCode)) {
                        kwXxjrFilterService.sendWithMe(userInfo, user);
                    } else if ("xbb".equals(channelCode)) {
                        kwXbbFilterService.sendXbb(userInfo, user);
                    } else if ("xycreditease".equals(channelCode)) {
                        userInfoService.sendXYCreditEase(userInfo, user);
                    } else if ("feidan8".equals(channelCode)) {
                        userInfoService.sendFeidan8(userInfo, user);
                    } else if ("ayd".equals(channelCode)) {
                        kwAydFilterService.sendAnyidai(userInfo, user);
                    } else if ("ayd2".equals(channelCode)) {
                        kwAydFilterService.sendAnyidai3(userInfo, user);
                    } else if ("cyph".equals(channelCode)) {
                        //获取上一天时间
                        long timemillis = DateUtils.getYesRanTime();
                        userInfo.setCreateDate(new Date(timemillis));
                        kwCyphFilterService.sendChangYuanpuhui(userInfo, user);
                    } else if ("ccic".equals(channelCode)) {
                        //获取上一天时间
                        long timemillis = DateUtils.getYesRanTime();
                        userInfo.setCreateDate(new Date(timemillis));
                        kwCcicFilterService.sendCCIC(userInfo, user);
                    }
                }
            }
        }
        return super.setResult(StatusCode.OK, "", StatusCode.codeMsgMap.get(StatusCode.OK));
    }


    //由出生日期获得年龄
    public int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }

}
